<?php
include('./init.php');
include('./helper.php');


function genTree($items) { 
	foreach ($items as $item) {
		$items[$item[OLD_PNAME]]['son'][$item[OLD_KEY]] = &$items[$item[OLD_KEY]]; 
	}
	return isset($items[0]['son']) ? $items[0]['son'] : array(); 
} 
function get_all_groups($data_new){
	$data_new2=array();
	foreach($data_new as $d){
		$data_new2[$d[OLD_KEY]]=$d;
	}
	return genTree($data_new2);
}
function groups_ul_tree($groups,$init=1,$extra=''){
	global $db;
	if($init==1){
		$obj=$groups;
	}else{
		$obj=isset($groups['son'])?$groups['son']:array();
		if(empty($obj)) return '';
	}
	$str=array();
	if($init==1){
		$str[]="<ul {$extra}>";
	}else{
		$str[]="<ul>";
	}
	$init++;
	
	$old_tablename=OLD_TABLENAME;
	$old_key=OLD_KEY;
	$old_catname=OLD_CATNAME;
	$old_pname=OLD_PNAME;
	
	$new_tablename=NEW_TABLENAME;
	$new_key=NEW_KEY;
	$new_catname=NEW_CATNAME;
	$new_pname=NEW_PNAME;
	$new_catid=NEW_CATID;
	
	$data_tablename=DATA_TABLENAME;
	
	
	foreach($obj as $s){
		if($s[$old_pname]==0){
			$diff=0;
		}else{
			$diff=$s[$old_pname]+NEW_CATID-1;
		}
		$new_catname=htmlspecialchars(addslashes($new_catname),ENT_QUOTES,'UTF-8');
		$_SESSION['store'][]=<<<st
		
		insert into {$new_tablename} ({$new_key},{$new_catname},{$new_pname}) values ('{$_SESSION['current_new_catid']}','{$s[$old_catname]}','{$diff}');
		
		
		
st;
		$db->exec("insert into cat_map (old_catid,new_catid) values ('{$s[$old_key]}','{$_SESSION['current_new_catid']}')");
		
		
		$_SESSION['current_new_catid']++;
		
		$str[]='<li><span><a href="#">'.$s[OLD_CATNAME].'</a></span>';
		$str[]=groups_ul_tree($s,$init,$extra);
		$str[]="</li>";
		
		
	}
	$str[]="</ul>";
	return implode("\r\n",$str);
}


isset($submit) or $submit='';

if($submit){
	
	$db->exec("truncate table cat_map");
	
	define('OLD_KEY',$old_key);
	define('OLD_CATNAME',$old_catname);
	define('OLD_PNAME',$old_pname);
	define('OLD_TABLENAME',$old_tablename);
	
	
	define('NEW_KEY',$new_key);
	define('NEW_CATNAME',$new_catname);
	define('NEW_PNAME',$new_pname);
	define('NEW_TABLENAME',$new_tablename);
	define('NEW_CATID',$new_catid);
	
	define('DATA_TABLENAME',$data_tablename);
	
	
	$_SESSION['store']=array();
	
	$_SESSION['current_new_catid']=$new_catid;
	
	$categorys=$db->mselect("select * from {$old_tablename} where {$old_key}>='{$old_catid}' order by ".OLD_KEY.' asc');
	$categorys=get_all_groups($categorys);
	$str=groups_ul_tree($categorys);
	
	if($show_ul)
		echo $str;
	
	echo implode("<br />",$_SESSION['store']);
	
	echo '<br />';
	$diff=NEW_CATID-1;
	
	$dts=$db->mselect("select * from cat_map");
	foreach($dts as $k=>$v){
		echo "{$v['old_catid']}------{$v['new_catid']}<br />";
	}
	//数据表增加一列 new_catid，进行联表更新
	//update data_table a set a.new_catid=(select b.new_catid from cat_map b where b.old_catid=a.old_catid limit 1);
	
	//update fv_category set parentid=parentid+12000 where moduleid=71 and parentid!=0;
	//update fv_nongyao set catid=catid+12000;
}

